package model

import (
	"errors"

	"github.com/jinzhu/gorm"
)

// UserInfo describes a user info
type UserInfo struct {
	gorm.Model
	Username string `json:"username"`
	Password string `json:"password"`
}

// CreateUser add a new user
func CreateUser(name, passWord string) interface{} {
	user := db.Save(&UserInfo{
		Username: name,
		Password: passWord,
	})
	return user.Value

}

// UserLogin login system
func UserLogin(name, passWord string) error {
	var user UserInfo
	db.Select("password").Where("username = ?", name).First(&user)
	if user.Password != passWord {
		return errors.New("password is not correct")
	}
	//todo println("add 认证 鉴权 逻辑")
	return nil
}

// GetUser get a single user
func GetUser(userID string) (result UserInfo, err error) {
	var user UserInfo
	db.First(&user, userID)
	if user.ID == 0 {
		err = errors.New("no user found")
		return UserInfo{}, err
	}
	resultUser := UserInfo{Username: user.Username, Password: user.Password}
	return resultUser, nil
}

// GetUserTatal get the all users number
func GetUserTatal(maps interface{}) (count int) {
	db.Model(&UserInfo{}).Where(maps).Count(&count)
	return
}

// ExistUserByName check the user is exist or not
func ExistUserByName(name string) (uint, bool) {
	var user UserInfo
	db.Select("id").Where("username = ?", name).First(&user)
	if user.ID > 0 {
		return user.ID, true
	}
	return 0, false
}

// ExistUserByID check the id is exist or not
func ExistUserByID(ID int) bool {
	var user UserInfo
	db.Select("id").Where("id = ?", ID).First(&user)
	if user.ID > 0 {
		return true
	}
	return false
}

// DeleteUser delete the user info from db
func DeleteUser(id int) bool {
	db.Where("id = ?", id).Delete(&UserInfo{})

	return true
}

// UpdateUser edit user info
func UpdateUser(id int, data interface{}) bool {
	db.Model(&UserInfo{}).Where("id = ?", id).Updates(data)

	return true
}
